package com.company.project.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.company.project.common.utils.DataResult;
import com.company.project.common.utils.Func;
import com.company.project.common.utils.StringUtil;
import com.company.project.common.utils.excel.ExcelUtils;
import com.company.project.entity.*;
import com.company.project.mapper.*;
import com.company.project.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@Service("tGhkhService")
public class TGhkhServiceImpl extends ServiceImpl<TGhkhMapper, TGhkhEntity> implements TGhkhService {
    @Resource
    private TWdkhMapper wdkhMapper;
    @Resource
    private TGhszMapper tGhszMapper;
    @Resource
    private TGzszMapper gzszMapper;
    @Resource
    private TGhkhMapper ghkhMapper;
    @Resource
    private UserService userService;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private HttpSessionService httpSessionService;
    @Resource
    private TSeatsMapper seatsMapper;
    @Resource
    private TGjjlMapper tGjjlMapper;
    @Resource
    private TGhszMapper gettGhszMapper;
    @Resource
    private RoleService roleService;
    @Resource
    private TGjjlService tGjjlService;
    @Resource
    private TSeatsMapper tSeatsMapper;

    @Override
    public DataResult saveFile(MultipartFile multipartFile, String id) {
        List<TGhkhEntity> list = new ArrayList<>();
        String khnameList = "";
        SysUser userInfo = userService.getUserInfo();
        TSeatsEntity tSeatsEntity = seatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery()
                .eq(TSeatsEntity::getAccountid, userInfo.getId()));
        try {
            JSONArray objects = ExcelUtils.readMultipartFile(multipartFile);
            List<Map<String,String>> javaObject = JSONArray.toJavaObject(objects, List.class);
            for(Map<String,String> map: javaObject) {
                String khname = map.get("*客户名称");
                String lxr = map.get("联系人");
                String lxdh = map.get("*联系电话");
                if (StringUtil.isNotBlank(lxdh)) {
                    String sple = "";
                    if (("" + lxdh).contains("，")){//13731151953，18631169798，13785112016
                        sple = "，";
                    } else if (("" + lxdh).contains("；")){
                        sple = "；";
                    } else if (("" + lxdh).contains(";")){
                        sple = ";";
                    } else if (("" + lxdh).contains(",")) {//13731151953，18631169798，13785112016
                        sple = ",";
                    }
                    if (StringUtil.isNotBlank(sple)) {
                        String[] l = lxdh.split(sple);
                        lxdh = l[0].toString();
                        if (!lxdh.contains("-"))  { //0311-88708100
                            BigDecimal bd = new BigDecimal("" + lxdh);
                            lxdh = bd.toBigInteger().toString();
                        }
                    }
                    if (!lxdh.contains("-")) {
                        //  判断是否为科学计数法（包含E、e、+等符号）
                        BigDecimal bd1 = new BigDecimal("" + lxdh);
                        lxdh = bd1.toBigInteger().toString();
                    }
                }
                String qtdh = map.get("其他手机号（多个手机号用;隔开）");
                if (StringUtil.isNotBlank(qtdh)) {
                    String sple = "";
                    if (("" + qtdh).contains("，")){//13731151953，18631169798，13785112016
                        sple = "，";
                    } else if (("" + qtdh).contains("；")){
                        sple = "；";
                    } else if (("" + qtdh).contains(";")){
                        sple = ";";
                    } else if (("" + qtdh).contains(",")) {//13731151953，18631169798，13785112016
                        sple = ",";
                    }

                    if (StringUtil.isNotBlank(sple)) {
                        String[] l = qtdh.split(sple);
                        qtdh = "";
                        for (int i = 0; l.length > i; i++) {
                            if (l[i].contains("-"))  { //0311-88708100
                                qtdh += l[i].toString() + ";";
                            } else {
                                if (phoneValidate(l[i])){
                                    BigDecimal bd = new BigDecimal("" + l[i]);
                                    qtdh += bd.toBigInteger().toString() + ";";
                                }
                            }
                        }
                        if (qtdh.length()>1){
                            qtdh = qtdh.substring(0, qtdh.length() - 1);
                        }
                    } else if (qtdh.indexOf("-") < -1) {
                        BigDecimal bd = new BigDecimal("" + qtdh);
                        qtdh = bd.toBigInteger().toString() + ";";
                    }
                }
                String khjb = map.get("客户级别");
                String khly = map.get("客户来源");
                String khdz = map.get("客户地址");
                String khhy = map.get("客户行业");
                String bz = map.get("备注");
                if (Func.isEmpty(khjb)) {
                    khjb = "0";
                }
                //已存在的客户名称不在入库
                Long aLong = 0l;
                if (id.contains(";")){
                    String[] split = id.split(";");
                    aLong = ghkhMapper.selectCount(Wrappers.<TGhkhEntity>lambdaQuery().eq(TGhkhEntity::getKhname, khname)
                            .eq(TGhkhEntity::getSsgh,split[0]).eq(TGhkhEntity::getSsghid,split[1])
                    );
                } else {
                    aLong = ghkhMapper.selectCount(Wrappers.<TGhkhEntity>lambdaQuery().eq(TGhkhEntity::getKhname, khname).eq(TGhkhEntity::getSsgh,id));
                }
                if (aLong > 0 || Func.isEmpty(khname)) {
                    khnameList += "客户名称(已存在):"+khname +";";
                    continue;
                }
                //效验联系电话是否正确
                if(!phoneValidate(lxdh) || Func.isEmpty(lxdh)) {
                    khnameList += "联系电话(格式异常):"+lxdh +";";
                    continue;
                }

                TGhkhEntity ghkh = new TGhkhEntity();
                ghkh.setKhname(khname);
                ghkh.setLxr(lxr);
                ghkh.setLxdh(lxdh);
                ghkh.setKhly(khly);
                ghkh.setKhjb(khjb);
                ghkh.setRktime(new Date());
                ghkh.setQdcs(0);
                ghkh.setRghyy("首次导入");
                if (id.indexOf(";")>-1){
                    String[] split = id.split(";");
                    ghkh.setSsgh(split[0]);
                    ghkh.setSsghid(split[1]);
                } else {
                    ghkh.setSsgh(id);
                }
                ghkh.setQtdh(qtdh);
                ghkh.setKhdz(khdz);
                ghkh.setKhhy(khhy);
                ghkh.setBz(bz);
                //添加入库
                save(ghkh);
                list.add(ghkh);
            }
            TGhszEntity tGhszEntity = new TGhszEntity();
            if (id.indexOf(";")>-1){
                String[] split = id.split(";");
                tGhszEntity = gettGhszMapper.selectOne(Wrappers.<TGhszEntity>lambdaQuery()
                        .eq(TGhszEntity::getGhmc, split[0]).eq(TGhszEntity::getId, split[1])
                        .eq(TGhszEntity::getSsgs, tSeatsEntity.getCorporatename()));
            } else {
                tGhszEntity = gettGhszMapper.selectOne(Wrappers.<TGhszEntity>lambdaQuery()
                        .eq(TGhszEntity::getGhmc, id)
                        .eq(TGhszEntity::getSsgs, tSeatsEntity.getCorporatename()));
            }
            tGhszEntity.setKhsl(tGhszEntity.getKhsl()+list.size());
            gettGhszMapper.updateById(tGhszEntity);
        }catch (RuntimeException e) {
            e.printStackTrace();
            return DataResult.fail("上传失败，请检查数据格式");
        }catch (Exception e) {
            e.printStackTrace();
            return DataResult.fail("上传失败！");
        }
        return DataResult.success(khnameList);
    }

    @Override
    public DataResult lingqu(List<String> ids) {
        try{
            SysUser userInfo = userService.getUserInfo();
            TSeatsEntity tSeatsEntity = seatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery()
                    .eq(TSeatsEntity::getAccountid, userInfo.getId()));
            Integer count = wdkhMapper.selectCountByUser(userInfo.getUsername());
            //根据公司名称查询规则
            TGzszEntity tGzszEntity = gzszMapper.selectOne(Wrappers.<TGzszEntity>lambdaQuery().eq(TGzszEntity::getSsgs, tSeatsEntity.getCorporatename()));
            if ((ids.size()+count) > tGzszEntity.getLqxz() && tGzszEntity.getLqxz() != 0) {
                return  DataResult.fail("超出领取限制：" + tGzszEntity.getLqsz());
            }
            Integer wcjhl = tGzszEntity.getWcjhl();//未成交回流
            Integer wgjhl = tGzszEntity.getWgjhl();//未跟进回流
            Integer hlDay = wcjhl > wgjhl ? wcjhl : wgjhl;
            //设置流入公海时间
            Date lrgh = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(lrgh);
            //加上规定时间
            calendar.add(Calendar.DAY_OF_MONTH, hlDay);
            lrgh = calendar.getTime();
            //没有规定时间 这是流入公海时间为空
            if (hlDay == 0){
                lrgh = null;
            }
            String ssgh = "";
            for (String id :ids) {
                TGhkhEntity ghkh = ghkhMapper.selectById(id);
                TWdkhEntity wdkh = new TWdkhEntity();
                wdkh.setKhname(ghkh.getKhname());
                wdkh.setLxr(ghkh.getLxr());
                wdkh.setLxdh(ghkh.getLxdh());
                wdkh.setSsxs(userInfo.getUsername());
                wdkh.setKhjb(ghkh.getKhjb());
                wdkh.setQdcs(0);
                wdkh.setRktime(new Date());
                wdkh.setKhly(ghkh.getKhly());
                wdkh.setCompany(tSeatsEntity.getCorporatename());
                wdkh.setQtdh(ghkh.getQtdh());
                wdkh.setBz(ghkh.getBz());
                wdkh.setKhdz(ghkh.getKhdz());
                wdkh.setKhhy(ghkh.getKhhy());
                wdkh.setLrghtime(lrgh);
                wdkh.setIsrlgh("1");
                wdkh.setSsgh(ghkh.getSsgh());
                wdkhMapper.insert(wdkh);
                ssgh = ghkh.getSsgh();
            }
            List<TGhszEntity> list = tGhszMapper.selectList(Wrappers.<TGhszEntity>lambdaQuery().eq(TGhszEntity::getGhmc, ssgh)
                    .eq(TGhszEntity::getSsgs, tSeatsEntity.getCorporatename()));
            TGhszEntity tGhszEntity = list.get(0);
            //删除公海数据
            removeByIds(ids);
            //变更客户数量
            tGhszEntity.setKhsl(tGhszEntity.getKhsl()- ids.size());
            tGhszMapper.updateById(tGhszEntity);
        }catch (Exception e) {
            e.printStackTrace();
            return DataResult.fail("领取异常，请联系管理员");
        }
        return DataResult.success();
    }

    @Override
    public DataResult fenpei(Map<String, Object> map) {
        List<String> ids = (List<String>) map.get("ids");
        String username = String.valueOf(map.get("username"));
        try{
            SysUser userInfo = userService.getUserInfo();
            TSeatsEntity tSeatsEntity = seatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery()
                    .eq(TSeatsEntity::getAccountid, userInfo.getId()));
            Integer count = wdkhMapper.selectCountByUser(username);
            //根据公司名称查询规则
            TGzszEntity tGzszEntity = gzszMapper.selectOne(Wrappers.<TGzszEntity>lambdaQuery().eq(TGzszEntity::getSsgs, tSeatsEntity.getCorporatename()));
            if ((ids.size()+count) > tGzszEntity.getLqsz() && tGzszEntity.getLqsz() != 0) {
                DataResult.fail("超出领取限制：" + tGzszEntity.getLqsz());
            }
            Integer wcjhl = tGzszEntity.getWcjhl();//未成交回流
            Integer wgjhl = tGzszEntity.getWgjhl();//未跟进回流
            Integer hlDay = wcjhl > wgjhl ? wcjhl : wgjhl;
            //设置流入公海时间
            Date lrgh = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(lrgh);
            //加上规定时间
            calendar.add(Calendar.DAY_OF_MONTH, hlDay);
            String ssgh = "";
            lrgh = calendar.getTime();
            for (String id :ids) {
                TGhkhEntity ghkh = ghkhMapper.selectById(id);
                TWdkhEntity wdkh = new TWdkhEntity();
                wdkh.setKhname(ghkh.getKhname());
                wdkh.setLxr(ghkh.getLxr());
                wdkh.setLxdh(ghkh.getLxdh());
                wdkh.setSsxs(username);
                wdkh.setKhjb(ghkh.getKhjb());
                wdkh.setQdcs(0);
                wdkh.setRktime(new Date());
                wdkh.setKhly(ghkh.getKhly());
                wdkh.setCompany(tSeatsEntity.getCorporatename());
                wdkh.setQtdh(ghkh.getQtdh());
                wdkh.setBz(ghkh.getBz());
                wdkh.setKhdz(ghkh.getKhdz());
                wdkh.setKhhy(ghkh.getKhhy());
                wdkh.setLrghtime(lrgh);
                wdkh.setIsrlgh("1");
                wdkh.setSsgh(ghkh.getSsgh());
                wdkhMapper.insert(wdkh);
                ssgh = ghkh.getSsgh();
            }
            List<TGhszEntity> list = tGhszMapper.selectList(Wrappers.<TGhszEntity>lambdaQuery().eq(TGhszEntity::getGhmc, ssgh)
                    .eq(TGhszEntity::getSsgs, tSeatsEntity.getCorporatename()));
            TGhszEntity tGhszEntity = list.get(0);            //删除公海数据
            removeByIds(ids);
            //变更客户数量
            tGhszEntity.setKhsl(tGhszEntity.getKhsl()- ids.size());
            tGhszMapper.updateById(tGhszEntity);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return DataResult.success();
    }

    @Override
    public DataResult infoData() {
        //通过用户 部门 递归查询部门id 再反查 我的客户表
        try {
            String userId = httpSessionService.getCurrentUserId();
            SysUser sysUser = userService.getById(userId);
            SysDept sysDept = sysDeptMapper.selectOne(Wrappers.<SysDept>lambdaQuery()
                    .eq(SysDept::getId, sysUser.getDeptId()));
            TSeatsEntity tSeatsEntity = tSeatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery().eq(TSeatsEntity::getAccountid, sysUser.getId()));
            TGzszEntity tGzszEntity = gzszMapper.selectOne(Wrappers.<TGzszEntity>lambdaQuery().eq(TGzszEntity::getSsgs, tSeatsEntity.getCorporatename()));
            Map<String, Object> map = new HashMap<>();
            //请选择客户来源  username  公海;
            List<String> username = wdkhMapper.selectUsername(sysDept.getDeptNo(),sysUser);
            //客户来源:搜索引擎、社交媒体、广告投放、客户推荐、展会资源、上门、个人资源、等等,或者支持自定义标签,让客户自己设置各自的;
            List<String> khly = new ArrayList<>();
            khly.add("搜索引擎");
            khly.add("社交媒体");
            khly.add("广告投放");
            khly.add("客户推荐");
            khly.add("展会资源");
            khly.add("上门");
            khly.add("个人资源");
            khly.add("特殊来源");
            khly.add("专属来源");
            khly.add("其他来源");

            List<TGhszEntity> tGhszEntities = tGhszMapper.selectList(Wrappers.<TGhszEntity>lambdaQuery()
                    .select(TGhszEntity::getGhmc,TGhszEntity::getId)
                    .like(TGhszEntity::getGhcy,userId)
                    .or()
                    .like(TGhszEntity::getGhgly,userId)
                    .or()
                    .like(TGhszEntity::getGhcybm,sysDept.getId()));
            map.put("username",username);
            map.put("khly",khly);
            map.put("gh",tGhszEntities);
            //是否隐藏
            List<SysRole> roleInfoByUserId = roleService.getRoleInfoByUserId(userId);
            List<String> collect = roleInfoByUserId.stream().map(e -> e.getName()).collect(Collectors.toList());
            if (Func.isNotEmpty(tGzszEntity)) {
                if (collect.contains("员工") || collect.contains("主管")) {
                    map.put("isyc", tGzszEntity.getIsyc());
                }
            }
            return DataResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return DataResult.fail("初始化选项失败，请联系管理员！");
        }
    }

    @Override
    public DataResult getDataById(String wdkhId) {
        Map<String,Object> map = new HashMap<>();
        TGhkhEntity ghkh = ghkhMapper.selectById(wdkhId);
        List<TGjjlEntity>  tGjjlEntityList = tGjjlMapper.selectListByWhtjId(ghkh.getWdkhid());
        map.put("wdkh",ghkh);
        map.put("gjjl",tGjjlEntityList);
        return DataResult.success(map);
    }

    //校验手机号
    public boolean phoneValidate(String phoneNumber){
        if (phoneNumber.equals("-")) return true;
        if (StringUtil.isNotBlank(phoneNumber) && !phoneNumber.isEmpty()){
            return Pattern.matches(
                    "^1[3-9]{1}\\d{9}$|" +
                            "^0\\d{3}-\\d{8}$|" +
                            "^0\\d{3}-\\d{7}$|" +
                            "^0\\d{2}-\\d{7}$|" +
                            "^0\\d{2}-\\d{8}$", phoneNumber);
        }
        return false;
    }
}